package cn.easybuy.utils;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;


public class ValidateImage {
	private int imgWidth=120;
	private int imgHeight=40;
	private int charCount=4;
	private int lineCount=30;
	private  char [] letters={'A','B','C','D','E','F','G','H','I','J','K','L','M',
				'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
				'2','3','4','5','6','7','8','9'};
	private Random random=new Random();
	BufferedImage image=null;
	/**
	 * @return
	 */
	public  String  createCode(){
		StringBuffer sb=new StringBuffer();
		 image=new BufferedImage(imgWidth,imgHeight,BufferedImage.TYPE_INT_RGB);
		Graphics g=image.getGraphics();
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, imgWidth, imgHeight);
		//设置每个字符的宽度
		int letterWidth=this.imgWidth/(this.charCount+2);
		//设置字体
		Font font=new Font("黑体",Font.ITALIC,letterWidth+6);
		g.setFont(font);
		//随机生成数字
		for (int i = 0; i < charCount; i++) {
			char temp=this.letters[random.nextInt(letters.length)];
			sb.append(temp);
			g.setColor(this.getRandomColor(0));
			int y=random.nextInt(imgHeight/2)+20;
			g.drawString(String.valueOf(temp), (i+1)*letterWidth, y);
				
		}
		//画干扰线
		for(int i=0;i<lineCount;i++){
			 g.setColor(this.getRandomColor(1));
			 //点要在图像的范围之内
			 int x1=random.nextInt(this.imgWidth);
			 int y1=random.nextInt(this.imgHeight);
			 int x2=x1+random.nextInt(20);
			 int y2=y1+random.nextInt(20);
			 g.drawLine(x1, y1, x2, y2);
		}
		return sb.toString();
	}
	public Color getRandomColor(int type){
		int r=0;
		int g=0;
		int b=0;
		if(type==0){
			r=random.nextInt(256-100);
			g=random.nextInt(256-100);
			b=random.nextInt(256-100);
		} else {
			r=random.nextInt(256-150)+120;
			g=random.nextInt(256-150)+120;
			b=random.nextInt(256-150)+120;
		}
		Color c=new Color(r,g,b);
		return c;
	}

	//将数据写入输出流
	public  void write(OutputStream os) throws IOException{
		ImageIO.write(image, "png", os);
		
	}

}
